<template>
  <a-select
    v-model:value="nameValue"
    allow-clear
    :placeholder="placeholder"
    :style="'width: ' + widthVal"
    show-search
    :filter-option="filterCodeOption"
    @change="handleChange"
  >
    <a-select-option
      v-for="item in stationList"
      :key="item.id"
      :label="item.name + item.namePinyin + item.namePy"
      :value="item.name"
    >
      {{ item.name }} - {{ item.namePinyin }} - {{ item.namePy }}
    </a-select-option>
  </a-select>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { StationApi } from '@/api/station';

const props = defineProps<{
  name: string;
  width?: string;
}>();

const placeholder = ref('请选择车站');
const nameValue = ref<string | null>(null);
const widthVal = ref<string>('');
const stationList = ref<any[]>([]);

watch(
  () => props.name,
  newName => {
    console.log('props', props);
    nameValue.value = newName || null;
  },
  {
    immediate: true,
  }
);

watch(
  () => props.width,
  newWidth => {
    widthVal.value = newWidth || '100%';
  },
  {
    immediate: true,
  }
);

const emit = defineEmits<{
  (e: 'update:name', name: string): void;
}>();

onMounted(() => {
  getStationList();
});

const getStationList = async (): Promise<void> => {
  const { data } = await StationApi.getStationListAll();
  console.log(data);
  stationList.value = data || [];
};
// 结合show-search一块使用，以及定义label属性value属性，全量匹配所有的额外名称
const filterCodeOption = (input: string, option: any): boolean => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 返回选中值所在的对象集合
const handleChange = (name: string): void => {
  emit('update:name', name);
  const res = stationList.value.find(item => item.name === name);
  return res;
};
</script>
